<!-- 进程管控 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px 16px; margin-bottom: 32px">
      <div style="display:flex;justify-content:space-between;">
        <div>
          <el-button type="primary" icon='el-icon-circle-plus-outline' @click="addClick()">添加规则</el-button>
          <span style="color:#d2d7e3;font-size:25px;margin-top:10px;padding-left:10px;"> 
            <el-tooltip class="item" effect="dark" placement="right">
              <i class="el-icon-question"></i> 
              <div style="width: 420px;" slot="content">通过拖动表格行来重新排列顺序, 系统按次序从上到下优先级执行。添加放到所有规则最后，插入表示在当前策略前插入一条规则</div>
            </el-tooltip>
          </span>
        </div>
      </div>
      <el-table stripe border :data="tableData" class="draggable-table" table-id="table1" row-key="RuleName"
        style="width: 100%; margin-top: 15px">
        <el-table-column label="序号" width="60" type="index"
          :index='(index) => { return (index + 1) + (this.pageNum - 1) * this.pageSize }'> </el-table-column>
        <el-table-column label="规则名称" prop="RuleName"  show-overflow-tooltip width="160px"></el-table-column>
        <el-table-column label="规则状态" show-overflow-tooltip prop="IsValid"  width="160px">
          <template slot-scope="{row}">
            <span style="color:#67C23A" v-if="row.IsValid === 1" type="success">正常</span>
            <span style="color:#F56C6C" v-else type="danger">失效</span>
          </template>
        </el-table-column>
        <el-table-column label="应用对象类型" show-overflow-tooltip prop="DeviceObjType" width="120px">
          <template slot-scope="{row}">
            <span>{{ DeviceObjTypeFormatter(row) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="应用对象" show-overflow-tooltip prop="DeviceObj" width="160px">
          <template slot-scope="{row}">
            <span>{{ getDeviceObjDisplay(row, DepartmentList, AssetsList) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注信息" show-overflow-tooltip prop="Descp" ></el-table-column>
        <el-table-column label="策略内容" show-overflow-tooltip prop="xxx"  :formatter="formatPolicy" ></el-table-column>
        <el-table-column label="操作" fixed="right" width="220px">
          <template slot-scope="scope">
            <el-button size="mini" type="success" @click="insertClick(scope.row, scope.$index)">插入</el-button>
            <el-button size="mini" type="primary" @click="changeClick(scope.row, scope.$index)">修改</el-button>
            <el-button size="mini" type="danger" @click="deleteClick(tableData, scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-dialog top="5vh" :close-on-click-modal="false" :close-on-press-escape=false
      :title="Action === 1 ? '添加规则'  : Action === 2 ? '修改规则' : '插入规则'" :visible.sync="dialogVisible" @close="getData()" v-el-drag-dialog
      width="1000px">
      <el-form label-width="130px" :model="accountForm" :rules="rules" ref="accountForm">
        <el-row class="ruleMain">
          <el-divider content-position="left">基本规则内容</el-divider>
          <el-col :xs="24" :sm="24" :lg="24">
            <el-form-item label='规则名称：' prop="RuleName">
              <el-input v-model.trim="accountForm.RuleName" :disabled="Action === 2" :maxlength="30"></el-input>
            </el-form-item>
            <el-form-item label='规则状态：' prop="IsVaclid">
              <el-radio v-model="accountForm.IsValid" :label="1">正常</el-radio>
              <el-radio v-model="accountForm.IsValid" :label="0">失效</el-radio>
            </el-form-item>
            <device-object-selector :form.sync="accountForm" />
            <el-form-item label="备注信息：" prop="Descp">
              <el-input placeholder="请输入备注" type="textarea" :rows="3" maxlength="50" v-model="accountForm.Descp"></el-input>
            </el-form-item>
            <el-form-item label='策略内容：' prop="IsVaclid">
              <el-checkbox style="width: 100%;" v-model="accountForm.ForbidCDROM" :true-label="1" :false-label="0">禁止光驱</el-checkbox>
              <el-checkbox style="width: 100%;" v-model="accountForm.ForbidCOM" :true-label="1" :false-label="0">禁止串口</el-checkbox>
              <el-checkbox style="width: 100%;" v-model="accountForm.ForbidParallelPort" :true-label="1" :false-label="0">禁止并口</el-checkbox>
              <el-checkbox style="width: 100%;" v-model="accountForm.Forbid1394" :true-label="1" :false-label="0">禁止1394</el-checkbox>
              <el-checkbox style="width: 100%;" v-model="accountForm.ForbidInfrared" :true-label="1" :false-label="0">禁止红外</el-checkbox>
              <el-checkbox style="width: 100%;" v-model="accountForm.ForbidWiFi" :true-label="1" :false-label="0">禁止wifi</el-checkbox>
              <el-checkbox style="width: 100%;" v-model="accountForm.ForbidBluetooth" :true-label="1" :false-label="0">禁止蓝牙</el-checkbox>
              <el-checkbox style="width: 100%;" v-model="accountForm.ForbidPCMCIA" :true-label="1" :false-label="0">禁止PCMCIA</el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider></el-divider>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false; getData()">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
  
<script>
import { connrequest } from '@/api/firstPage'
import { toTree } from "@/utils/index.js";
import { getDeviceObjDisplay, DeviceObjTypeFormatter } from '@/utils/index.js';
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import Sortable from "sortablejs";
import DeviceObjectSelector from '@/components/DeviceObjectSelector'
export default {
  directives: { elDragDialog },
  components: {
    DeviceObjectSelector
  },
  data() {
    return {
      pageNum: 1,
      pageSize: 10,
      tableData: [],
      RoleList: [],
      DepartmentList: [],
      AssetsList: [],
      DeviceObjList: [],
      Action: 0,
      dialogVisible: false,
      accountForm: {},
      auditAction: 1,
      auditdialog: false,
      auditForm: {
        IsValid: 1,
        DeviceObjType: 1,
        ForbidCDROM: 0,
        ForbidCOM: 0,
        ForbidParallelPort: 0,
        Forbid1394: 0,
        ForbidInfrared: 0,
        ForbidWiFi: 0,
        ForbidBluetooth: 0,
        ForbidPCMCIA: 0,
      },
      OBJList: '',
      rules: {
        RuleName: [
          { required: true, message: "请输入规则名称" }
        ],
      },
    }
  },
  watch: {
    Action() {
      this.$nextTick(() => {
        this.initSort()
      })
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.GetDepartment()
    this.GetDevice()
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.initSort();
  },
  methods: {
    DeviceObjTypeFormatter,
    getDeviceObjDisplay,
    // 获取所有部门
    async GetDepartment() {
      const res = await connrequest('GetDepartment')
      this.DepartmentList = res.Data
    },
    // 获取所有资产
    async GetDevice() {
      const data = {
        Paging: {
          QueryPageNo: 1,
          QueryPageLength: 100000
        },
      }
      const res = await connrequest('GetDevice', data)
      this.AssetsList = res.Data
    },
    initSort() {
      document.querySelectorAll('.draggable-table').forEach(table => {
        const el = table.querySelector('.el-table__body-wrapper > table > tbody');
        const tableId = table.getAttribute('table-id');
        new Sortable(el, {
          animation: 500,
          onEnd: async (evt) => {
            if (tableId === 'table1') {
              const currRow = this.tableData.splice(evt.oldIndex, 1)[0];
              this.tableData.splice(evt.newIndex, 0, currRow);
              const newData = [];
              this.tableData.forEach((item, index) => {
                newData[index] = {
                  id: item.id,
                  rank: index + 1
                };
              });
              const data = {
                Filter: {
                  FileName: 'rule_peripheral_device.json'
                },
                Data: this.tableData
              };
              const res = await connrequest('SetUICommonParam', data);
              if (res.Status.StatusCode === 0) {
                this.$message.success('排序成功');
                this.getData();
              }
            }
          }
        });
      });
    },
    formatPolicy(row) {
      const policyContent = [];
      if (row.ForbidCDROM === 1) policyContent.push("禁止光驱");
      if (row.ForbidCOM === 1) policyContent.push("禁止串口");
      if (row.ForbidParallelPort === 1) policyContent.push("禁止并口");
      if (row.Forbid1394 === 1) policyContent.push("禁止1394");
      if (row.ForbidInfrared === 1) policyContent.push("禁止红外");
      if (row.ForbidWiFi === 1) policyContent.push("禁止WiFi");
      if (row.ForbidBluetooth === 1) policyContent.push("禁止蓝牙");
      if (row.ForbidPCMCIA === 1) policyContent.push("禁止PCMCIA");
      return policyContent.join("，"); // 使用逗号分隔
    },
    async getData() {
      const data = {
        Filter: {
          FileName: 'rule_peripheral_device.json'
        }
      }
      const res = await connrequest('GetUICommonParam', data)
      this.tableData = res.Data || []
    },
    addClick() {
      this.Action = 1;
      this.$nextTick(() => {
        // 等待组件挂载
        this.accountForm = {
          IsValid: 1,
          DeviceObjType: 1,
          ForbidCDROM: 0,
          ForbidCOM: 0,
          ForbidParallelPort: 0,
          Forbid1394: 0,
          ForbidInfrared: 0,
          ForbidWiFi: 0,
          ForbidBluetooth: 0,
          ForbidPCMCIA: 0,
        };
        this.$refs['accountForm'].resetFields();
      });
      this.dialogVisible = true;
    },
    insertClick(row, index) {
      this.Action = 3
      this.tableindex = index
      this.$nextTick(() => {
        // 等待组件挂载
        this.accountForm = {
          Protocol: 'ANY',
          IsValid: 1,
          DeviceObjType: 1,
          DstPortType: 1
        };
        this.$refs['accountForm'].resetFields();
      });
      this.dialogVisible = true;
    },
    changeClick(row, index) {
      this.tableindex = index
      this.Action = 2
      this.$nextTick(() => {
        this.accountForm = { ...row, ProcObjs: row.ProcObjs }
        this.$refs['accountForm'].resetFields();
      })
      this.dialogVisible = true
    },
    deleteClick(tableData, index) {
      this.$confirm('此操作将永久删除该规则, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        tableData.splice(index, 1)
        const data = {
          Filter: {
            FileName: 'rule_peripheral_device.json'
          },
          Data: tableData
        }
        const res = await connrequest('SetUICommonParam', data)
        if (res.Status.StatusCode === 0) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getData()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    submit() {
      this.$refs['accountForm'].validate(async (valid) => {
        if (valid) {
          if (this.accountForm.DeviceObjType === 2) {
            if (!this.accountForm.DeviceObj || this.accountForm?.DeviceObj?.length === 0) {
              this.$message.error('请选择部门')
              return false
            }
          }
          if (this.accountForm.DeviceObjType === 8) {
            if (!this.accountForm.DeviceObj || this.accountForm?.DeviceObj?.length === 0) {
              this.$message.error('请选择角色')
              return false
            }
          }
          if (this.accountForm.DeviceObjType === 6) {
            if (!this.accountForm.DeviceObj || this.accountForm?.DeviceObj?.length === 0) {
              this.$message.error('请选择资产')
              return false
            }
          }
          if (this.Action !== 2 && this.tableData.findIndex(item => item.RuleName === this.accountForm.RuleName) !== -1) {
            this.$message.error('该规则已经存在')
            return false
          }
          let data = {}
          if (this.Action === 1) {
            data = {
              Filter: {
                FileName: 'rule_peripheral_device.json'
              },
              Data: [
                ...this.tableData,
                {
                  ...this.accountForm,
                  RuleID: Math.floor(Date.now() / 1000)
                }
              ]
            }
          }
          if (this.Action === 2) {
            this.tableData[this.tableindex] = this.accountForm
            data = {
              Filter: {
                FileName: 'rule_peripheral_device.json'
              },
              Data: this.tableData
            }
          }
          if (this.Action === 3) {
            this.tableData.splice(this.tableindex, 0, { ...this.accountForm, RuleID: Math.floor(Date.now() / 1000) })
            data = {
              Filter: {
                FileName: 'rule_peripheral_device.json'
              },
              Data: this.tableData
            }
          }
          const res = await connrequest('SetUICommonParam', data)
          if (res.Status.StatusCode === 0) {
            this.$message.success(this.Action == 1 ? '添加成功' : '修改成功')
            this.getData()
            this.dialogVisible = false
          }
        }
      })
    },
  }
}
</script>